﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Yuebon.Commons.Cache;
using Yuebon.Commons.IoC;
using Yuebon.Commons.Json;
using Yuebon.Commons.Models;
using Yuebon.Security.Application;
using Yuebon.Security.Application.SSO;
using Yuebon.Security.Dtos;

namespace Yuebon.WebApi.Areas.SSO.Controllers
{
    /// <summary>
    ///  sso验证
    /// <para>其他站点通过后台Post来认证</para>
    /// <para>或使用静态类Yuebon.Security.Application.SSO.AuthHelper访问</para>
    /// </summary>
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class CheckController : ControllerBase
    {
        private SSOAuthHelper ssoAuthHelper=IoCContainer.Resolve<SSOAuthHelper>();
       
        /// <summary>
        /// 检验token是否有效
        /// </summary>
        /// <param name="token">The token.</param>
        /// <param name="requestid">备用参数.</param>
        [HttpGet("GetStatus")]
        public CommonResult<bool> GetStatus(string token, string requestid = "")
        {
            var result = new CommonResult<bool>();
            try
            {
                YuebonCacheHelper yuebonCacheHelper = new YuebonCacheHelper();
                result.Result = yuebonCacheHelper.Get(token) != null;
                result.Success = true;
            }
            catch (Exception ex)
            {
                result.ErrCode = "500";
                result.ErrMsg = ex.Message;
            }

            return result;
        }

        /// <summary>
        /// 根据token获取用户及用户可访问的所有资源
        /// </summary>
        /// <param name="token"></param>
        /// <param name="requestid">备用参数.</param>
        [HttpGet("GetUser")]
        public CommonResult<UserWithAccessedCtrls> GetUser(string token, string requestid = "")
        {
            var result = new CommonResult<UserWithAccessedCtrls>();
            try
            {
                YuebonCacheHelper yuebonCacheHelper = new YuebonCacheHelper();
                var user = JsonConvert.DeserializeObject<UserAuthSession>(yuebonCacheHelper.Get(token).ToJson());
                if (user != null)
                {
                    result.Result =new AuthorizeApp().GetAccessedControls(user.Account);
                    result.Success = true;
                }
            }
            catch (Exception ex)
            {
                result.ErrCode = "500";
                result.ErrMsg = ex.InnerException != null
                    ? "YuebonAuth.WebAPI数据库访问失败:" + ex.InnerException.Message
                    : "YuebonAuth.WebAPI数据库访问失败:" + ex.Message;
            }

            return result;

        }

        /// <summary>
        /// 根据token获取用户名称
        /// </summary>
        /// <param name="token"></param>
        /// <param name="requestid">备用参数.</param>
        [HttpGet("GetUserName")]
        public CommonResult<string> GetUserName(string token, string requestid = "")
        {
            var result = new CommonResult<string>();
            try
            {
                YuebonCacheHelper yuebonCacheHelper = new YuebonCacheHelper();
                var user = yuebonCacheHelper.Get<UserAuthSession>(token);
                if (user != null)
                {
                    result.Result = user.Account;
                    result.Success = true;
                }
            }
            catch (Exception ex)
            {
                result.ErrCode = "500";
                result.ErrMsg = ex.Message;
            }

            return result;
        }
        /// <summary>
        /// 登录接口
        /// </summary>
        /// <param name="request">登录参数</param>
        /// <returns></returns>
        [HttpPost("Login")]
        public LoginResult Login([FromBody]PassportLoginRequest request)
        {
            var result = new LoginResult();
            try
            {
                result = ssoAuthHelper.Validate(request);
            }
            catch (Exception ex)
            {
                result.ErrCode = "500";
                result.ErrMsg = ex.Message;
            }

            return result;
        }

        /// <summary>
        /// 注销登录
        /// </summary>
        /// <param name="token"></param>
        /// <param name="requestid">备用参数.</param>
        [HttpPost("Logout")]
        public bool Logout(string token, string requestid = "")
        {
            try
            {
                YuebonCacheHelper yuebonCacheHelper = new YuebonCacheHelper();
                yuebonCacheHelper.Remove(token);
                var user = yuebonCacheHelper.Get<UserAuthSession>(token);
                yuebonCacheHelper.Remove("User_Function_" + user.UserId);
                yuebonCacheHelper.Remove("User_Menu_" + user.UserId);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
    }
}